package com.eastfair.certificate.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.annotation.annotation.base.BaseControllerInfo;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.annotation.annotation.tenant.TenantAuth;
import com.eastfair.auth.dto.RoleDTO;
import com.eastfair.certificate.dto.*;
import com.eastfair.certificate.entity.Certificate;
import com.eastfair.certificate.entity.CertificateIndex;
import com.eastfair.certificate.service.CertificateService;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import com.eastfair.boot.controller.SuperController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.certificate.service.FormFieldGroupService;
import com.eastfair.certificate.util.FrameMarker;
import com.eastfair.certificate.vo.CertificateVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.echo.core.EchoService;
import com.eastfair.core.base.R;
import com.eastfair.venueservice.entity.ExhibitionManage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static com.eastfair.core.base.R.SUCCESS_CODE;


/**
 * <p>
 * 前端控制器
 * 证件设置
 * </p>
 *
 * @author ligang
 * @date 2022-07-21
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/certificate")
@Api(value = "Certificate", tags = "证件设置")
@PreAuth(replace = "certificate:certificate:")
public class CertificateController extends SuperController<CertificateService, Long, Certificate, CertificatePageQuery, CertificateSaveDTO, CertificateUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Autowired
    FrameMarker frameMarker;

    @Autowired
    FormFieldGroupService formFieldGroupService;

    @Override
    public void handlerResult(IPage<Certificate> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<Certificate> certificateList = list.stream().map((map) -> {
            Certificate certificate = Certificate.builder().build();
            //TODO 请在这里完成转换
            return certificate;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(certificateList));
    }


    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<CertificatePageQuery> params) {
        CertificatePageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 新增
     *
     * @param certificateDTO 保存参数
     * @return 实体
     */
    @ApiOperation(value = "新增")
    @PostMapping("/addCertificate")
    @SysLog("新增证件")
    public R<CertificateVO> addCertificate(@RequestBody @Validated({CertificateDTO.addCertificate.class}) CertificateDTO certificateDTO) {
        return baseService.saveCertificate(certificateDTO);
    }


    /**
     * 更新证件审核项
     *
     * @param certificateDTO 证件实体
     * @return
     */
    @ApiOperation(value = "更新证件审核项", notes = "更新证件审核项")
    @PostMapping("/updateAuth")
    @TenantAuth()
    @SysLog("更新证件审核项")
    public R updateAuth(@RequestBody CertificateDTO certificateDTO) {
//        if (certificateDTO.getFirstAuthId() == null && certificateDTO.getSecondAuthId() == null) {
//            return R.fail("请选择审核项");
//        }
        Certificate certificate = baseService.getByIdCache(certificateDTO.getId());
        if (certificate != null) {
            certificate.setFirstAuthId(certificateDTO.getFirstAuthId());
            if (certificateDTO.getFirstAuthId() != null) {
                certificate.setFirstAuthTime(LocalDateTime.now());
            }
            certificate.setSecondAuthId(certificateDTO.getSecondAuthId());
            if (certificateDTO.getSecondAuthId() != null) {
                certificate.setSecondAuthTime(LocalDateTime.now());
            }
//            baseService.updateById(certificate);
            //手动更新空值
            UpdateWrapper<Certificate> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(Certificate::getId, certificate.getId())
                    .set(Certificate::getFirstAuthId, certificate.getFirstAuthId())
                    .set(Certificate::getFirstAuthTime, LocalDateTime.now())
                    .set(Certificate::getSecondAuthId, certificate.getSecondAuthId())
                    .set(Certificate::getSecondAuthTime, LocalDateTime.now());
            boolean b = baseService.update(updateWrapper);
            //删除缓存
            baseService.delCache(certificate);
        }
        return R.success(certificate);
    }


    /**
     * 新增
     *
     * @return 实体
     */
    @ApiOperation(value = "查询")
    @GetMapping("/list")
    @TenantAuth()
    public R<List<CertificateVO>> list() {
        return R.success(baseService.doToVos(baseService.list(null, null)));
    }


    /**
     * 分页查询审核表单
     *
     * @param params
     * @return 是否成功
     */
    @ApiOperation(value = "分页查询审核表单", notes = "分页查询审核表单")
    @PostMapping("/pageCertificate")
    @BaseControllerInfo()
    @TenantAuth()
    public R<IPage<CertificateVO>> pageFirstAuthForm(@RequestBody @Valid PageParams<CertificateDTO> params) {
        return R.success(baseService.pageCertificate(params));
    }


    /**
     * 新增
     *
     * @return 实体
     */
    @ApiOperation(value = "查询")
    @PostMapping("/certificateList")
    @TenantAuth()
    public R<List<CertificateVO>> certificateList(@RequestBody CertificateDTO certificateDTO) {
        List<Long> ids = new ArrayList<>();
        ids.add(2059534265182588928L);
        ids.add(2079311181000216576L);
        return R.success(baseService.doToVos(baseService.list(certificateDTO, null)));
    }


    /**
     * 同步业务表单
     *
     * @param id
     * @return 是否成功
     */
    @ApiOperation(value = "同步业务表单", notes = "同步业务表单")
    @GetMapping("/sycnsubmitForm")
    @BaseControllerInfo()
    public R sycnsubmitForm(Long id) {
        FormFieldSubsystemDTO formFieldSubsystemDTO = new FormFieldSubsystemDTO();
        formFieldSubsystemDTO.setRelatedId(id);
        return formFieldGroupService.sycnsubmitForm(formFieldSubsystemDTO);
    }

    /**
     * test
     *
     * @return 是否成功
     */
    @ApiOperation(value = "testFtl", notes = "test")
    @GetMapping("/testFtl")
    @BaseControllerInfo()
    public R testFtl(HttpServletResponse response) {
        Map root = new HashMap();
        frameMarker.exportFile("test.ftl", root, "test.doc", response);
        return R.success();
    }

    /**
     * test
     *
     * @return 是否成功
     */
    @GetMapping("/get")
    @BaseControllerInfo()
    public R getByid2(Long id) {
        return R.success(baseService.getByIdCache(id));
    }

    /**
     * 系统字体
     *
     * @return
     */
    @GetMapping("/querFontType")
    public R querFontType(String fontType) {
        log.info("querFontType type is {}",fontType);
        Locale local = null;
        if ("zh".equals(fontType)) {
            local = new Locale("zh", "CN");
        } else {
            local = new Locale("en", "US");
        }
        //获取系统字体
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontName = e.getAvailableFontFamilyNames(local);
        log.info("querFontType fontName is {}",JSONObject.toJSONString(fontName));
        return R.success(fontName);
    }


}
